<?php
class Users_UserLoginController  extends Zend_Controller_Action
{
private $_token;
protected $stdClass;
protected $data;
	public function init()
	{
	$this->_helper->getHelper('AjaxContext')
        ->addActionContext('check','json')
        ->addActionContext('checking','json')
        ->addActionContext('input-validate','json')
        ->initContext();
	}
	
	public function preDispatch()
	{

	}
	
	public function indexAction()
	{}
	public function editprofileAction()
	{
		$auth=Zend_Auth::getInstance()->getIdentity();

		if($auth->status === 'user' || $auth->status === 'admin' || $auth->status === 'demo_admin' ){//&& isset($auth->login)
		$profile=new Myblog_Form_UserProfile();
		$this->view->profile = $profile;
		if(isset($auth->login) && $auth->status === 'user'){

		$q=Doctrine_Query::create()
			->from('Myblog_Model_Users u')
			->where('u.userlogin=?',$auth->login)
			->fetchArray();

		if(!empty($q[0]['avatar'])){
			$ava=$profile->getElement('avatar');
			$ava->src=$q[0]['avatar'];
		}
		else{
				$q2=Doctrine_Query::create()
					->update('Myblog_Model_Users u')
					->where('u.userlogin=?',$auth->login)
					->set('u.avatar','?','images/avatars/noavatar.png')
					->execute();
			}
		    if(!empty($q)){
			    $this->view->profile->populate($q[0]);
		    }
        }elseif($auth->status === 'admin' || $auth->status === 'demo_admin'){

            $this->view->profile->populate($auth->data[0]);
            if(!empty($auth->data[0]['avatar'])){
                $ava=$profile->getElement('avatar');
                $ava->src=$auth->data[0]['avatar'];
            }
        }
			if($this->getRequest()->isPost() && $profile->isValid($this->_getAllParams()))
			    {
				$val = $profile->getValues();
				$q3=Doctrine_Query::create()
					->update('Myblog_Model_Users u')
					->where('u.userlogin=?',$auth->login)
					->set('u.userlogin','?',$val['userlogin'])
					->set('u.username','?',$val['username'])
					->set('u.email','?',$val['email'])
					->execute();
					Zend_Auth::getInstance()->getIdentity()->login=$val['userlogin'];
					//$this->_redirect($this->view->url());
                    $this->_helper->getHelper('FlashMessenger')
                        ->addMessage('Профайл успешно обновлен.');
                    $this->redirect('user/userprofile');
				}
		}else{
            throw new Zend_Controller_Action_Exception('Invalid input');
        }
	}
    public function inputValidateAction(){
       //move_uploaded_file($_FILES["image"]["tmp_name"],'images/avatars/'.$_FILES["image"]["name"]);
        $auth= Zend_Auth::getInstance();
        if(isset($auth->getIdentity()->email)){
            $email = $auth->getIdentity()->email;
        }
        $editForm = new Myblog_Form_UserProfile();

        $editForm->isValidPartial($this->getRequest()->getPost());
        $mess = $editForm->getMessages();

        foreach($mess as $m=>$k){
            $this->view->$m=$k;
        }
    }
    public function avatarUploadAction(){

        if($this->getRequest()->isPost()){
            $adapter = new Zend_File_Transfer_Adapter_Http();
        try{
            $options = array('width' => 100, 'height' => 100);

            $filename=pathinfo($adapter->getFileName());
            $newfilename=uniqid().'.'.$filename['extension'];

            $adapter->addFilter(new Zend_Filter_File_ImageResize($options))
                ->addFilter('Rename',array('target'=>'images/avatars/'.$newfilename,'overwrite'=>true))
                ->setDestination('images/avatars/');

            $adapter->addValidators(array(
                                         array('isImage'),
                                         array('Extension',false,array('jpg','jpeg','png','gif')),
                                         array('Count',false,2),
                                         array('FilesSize',false,array('min' => '5kB', 'max' => '2MB')),
                                         array('ImageSize',false,array('minwidth'=>50,'maxwidth'=>1920,
                                                                       'minheight'=>50,'maxheight'=>1080))
                                    ));
            if($adapter->receive() & $adapter->isValid()){//&
                $adapter->getFile();
            }
        }catch(Exception $e){
           $e->getMessage();
        }
            $auth = Zend_Auth::getInstance()->getIdentity();
            if(count($adapter->getErrors())){
                $errorsCont = array();
                $errors = $adapter->getMessages();
                foreach($errors as $v=>$k){
                    $errorsCont[] = $k;
                }
                $this->view->errors = $errorsCont;
            }else{
                Myblog_Model_Users::addAvatar($adapter->getFileName(),$auth->id);
                $this->view->avatar = $adapter->getFileName();
            }
        }
    }
	public function loginAction(){
    	if($this->getRequest()->isXmlHttpRequest())
            {
    	    $this->_helper->getHelper('layout')->disableLayout();
    	    $form = new Myblog_Form_UserLogin;
    	    $form->isValid($this->_getAllParams());
    	    $msg = $form->getMessages();
    	    header("Content-Type: application/json");
    	    $this->_helper->json($msg);
    	    }
            if($this->getRequest()->isPost())
            {
    	    $data = $this->_getAllParams();
    	    $f=array('StripTags','StringTrim','StringToLower');
    	    $v=array('NotEmpty','Alnum');
    	    $input = new Zend_Filter_Input($f,$v);
    	    $input->setData($data);
    	if($input->isValid())
			{
			$pass=sha1($input->getEscaped('userpassword'));
			$auth=Zend_Auth::getInstance();
			$adapter=new Myblog_Auth_Adapter_Doctrine($data['login'],$pass);
			$result=$auth->authenticate($adapter);
			$userData=$adapter->getResultArray();

			if($result->isValid() && $userData[0]['role'] === 'admin' || $userData[0]['role'] === 'demo_admin'){
                $zendAuth = Zend_Auth::getInstance();
                $datas = $zendAuth ->getStorage()->read();
                $storage_data = new stdClass();
                $storage_data->data = $adapter->getResultArray();
                $storage_data->data[0]['logindatetime'] = date('m/d/Y H:i:s');
                $storage_data->status = $storage_data->data[0]['role'];

                $admins = new Myblog_Model_Admins;
                $admins->login = $storage_data->data[0]['userlogin'];
                $admins->logintime =  $storage_data->data[0]['logindatetime'];
                $admins->user_id = $storage_data->data[0]['id'];
                $admins->save();
                $zendAuth->getStorage()->write($storage_data);

                $session=new Zend_Session_Namespace('Zend.Auth');
                $session->setExpirationSeconds(60*60);
                $session->user=$adapter->getResultArray('password');
                $session->lock();
                $this->_helper->getHelper('FlashMessenger')
                    ->addMessage('Вы успешно авторизовались!');
                $this->redirect('/user/login/success');
            }elseif($result->isValid() && $userData[0]['role'] === 'user' || $userData[0]['role'] === 'guest'){
					if($data['checkbox'] == 1)
						{
						Zend_Session::rememberMe(7*24*60*60);
						}
						$session=new Zend_Session_Namespace('user.auth');
                        $session->setExpirationSeconds(60*60*24);
                        $session->lock();

						if(isset($session->requestURL)){
						$url=$session->requestURL;
						unset($session->requestURL);
						$this->_redirect($url);
					}else{
								$auth = Zend_Auth::getInstance();
								$storage_data = new stdClass();
								$storage_data->status = $userData[0]['role'];
								$storage_data->email = $userData[0]['email'];
								$storage_data->regtime = $userData[0]['reg_time'];
								$storage_data->avatar = $userData[0]['avatar'];
								$storage_data->login = $userData[0]['userlogin'];
								$storage_data->name = $userData[0]['username'];
                                $storage_data->id = $userData[0]['id'];
							 	$auth->getStorage()->write($storage_data);

							$this->_helper->getHelper('FlashMessenger')
									->addMessage('Вы успешно авторизовались!');
							$this->redirect('/user/login/success');
						}
				}else{
                        $this->view->message='Вы ввели несуществующую или неактивную учетную запись';
                        $this->getResponse()->setHeader('Refresh','3; URL=/main');
				}
			}
	    }
	}
			public function uploadAction()
			{
			$auth=Zend_Auth::getInstance();
			$auth=$auth->getIdentity();				
			$this->_helper->viewRenderer->setNoRender(true);
			$this->_helper->getHelper('layout')->disableLayout();
			
				//-----------------------------------
			try{
			$upload = new Zend_File_Transfer();
			//$s=$_FILES['uploadfile']['size'];
		
			$files = $upload->getFileInfo();
			
			$size = $upload->getFileSize();
			}catch(Exception $e){
			$limit=$_FILES['uploadfile']['size'];
				if($limit==null)
				{
				header("Content-Type: application/json");	
				$this->_helper->json(array('status'=>'limitmaxsizephp'));
				}
				header("Content-Type: application/json");	
				$this->_helper->json(array('status'=>'phplimitsize'));

			}
			if($size > '5.00kB')
			{
				header("Content-Type: application/json");
				$this->_helper->json(array('status'=>'limitmaxsize'));
				return ;
			}
			//-----------------------------------
			
			
			$uploaddir = 'images/avatars/';
			$file = $uploaddir.basename($_FILES['uploadfile']['name']); 
			$ext = substr($_FILES['uploadfile']['name'],strpos($_FILES['uploadfile']['name'],
			'.'),strlen($_FILES['uploadfile']['name'])-1); 
			$filetypes = array('.jpg','.gif','.bmp','.png','.JPG','.BMP','.GIF','.PNG','.jpeg','.JPEG');
		
			if(!in_array($ext,$filetypes))
			{
			header("Content-Type: application/json");
			$this->_helper->json(array('status'=>'extension not supporting'));
			return;
			}
			
			$filename=pathinfo($upload->getFileName());
			$newfilename=uniqid().'.'.$filename['extension'];
			$upload = new Zend_File_Transfer_Adapter_Http();
			$options = array('width' => 100, 'height' => 100);
			
			$upload->addFilter(new Zend_Filter_File_ImageResize($options))
							->addFilter('Rename',array('target'=>'images/avatars/'.$newfilename,'overwrite'=>true))
							->setDestination('images/avatars/');

						if (!$upload->receive()) 
						{
							header("Content-Type: application/json");
				 			$this->_helper->json(array('status'=>'error'));
								
								return;
						}
						
						$del = Doctrine_Query::create()
							->from('Myblog_Model_Users u')
							->where('u.userlogin=?',$auth->login)
							->fetchArray();
						if(!empty($del[0]['avatar']))	
						{
						if($del[0]['avatar'] !=='images/avatars/noavatar.png'){
						unlink($del[0]['avatar']);}
						}
						
						$q=Doctrine_Query::create()
								->update('Myblog_Model_Users u')
								->where('u.userlogin=?',$auth->login)
								->set('u.avatar','?',$uploaddir.$newfilename)
								->execute();
						
							//header("Content-Type: application/json");
				 			echo json_encode(array('status'=>'success','filename'=>$newfilename));
				 		//$this->_helper->json
				 	
			}
	public function passrecoveryAction()
	{
	$passrecform = new Myblog_Form_PassRecovery;
	$this->view->recform = $passrecform;

        if($this->getRequest()->isPost() && $passrecform->isValid($this->getRequest()->getPost()) && !$this->getRequest()->isXmlHttpRequest()){
           $email = $this->getRequest()->getParam('email');
            $ver = Doctrine_Query::create()
                ->from('Myblog_Model_Users u')
                ->where('u.email=?',$email)
                ->fetchArray();
            if(count($ver)){
            $time = date('Y-m-d H:i:s');
            $token = sha1(uniqid($email, true));
            $config = array(//'ssl' => 'tls',
                            'port' => 25,
                            'auth' => 'login',
                            'username' => 'zhan27.87@mail.ru',
                            'password' => 'diaszhanara2012');

           $tr = new Zend_Mail_Transport_Smtp('smtp.mail.ru', $config);

            $mail = new Zend_Mail('UTF-8');
            $mail->setFrom('zhan27.87@mail.ru', $this->getRequest()->getHttpHost());
            $mail->addTo($email, '');
            $mail->setSubject('Восстановление пароля.');
            $mail->setBodyText("
            ");
            $mail->setBodyHtml("

               <p>Для изменения пароля перейдите по ссылке.</p>
               <a href=http://".$this->getRequest()->getHttpHost()."/verification/".$token.">Восстановление пароля</a>

            ");
            $mail->send($tr);
                if($mail){
                    $user = Doctrine_Query::create()
                        ->from('Myblog_Model_Users u')
                        ->where('u.email=?',$email)
                        ->fetchArray();
                    if($user){
                        $tokens = new Myblog_Model_Tokens();
                        $tokens->user_id = $user[0]['id'];
                        $tokens->created_dt = $time;
                        $tokens->token = $token;
                        $tokens->save();
                    }


                    $this->_helper->getHelper('FlashMessenger')->addMessage('На e-mail '.$email.' отправлено письмо со ссылкой на восстановление пароля.');
                    $this->redirect('/user/sendtoken/success');
                }else{
                    $this->_helper->getHelper('FlashMessenger')->addMessage('Ошибка восстановления пароля, повторите процедуру позже');
                    $this->redirect('/user/login/failed');
                }
            }else{
                $this->_helper->getHelper('FlashMessenger')->addMessage('Пользователь с таким E-mail не зарегистрирован или отключен');
                $this->redirect('/user/login/failed');
            }


        }

	}
    public function verificationTokenAction(){

        $token = $this->getRequest()->getParam('token');

        if(isset($token) && !empty($token) && mb_strlen($token,'utf-8') === 40){
           // var_dump($this->getRequest()->getParam('token'));exit;

            $verifycation = Doctrine_Query::create()
                ->from('Myblog_Model_Tokens t')
                ->where('t.token=?',$token)
                ->fetchArray();

            if($verifycation){

                $now = time();
                $created_dt = strtotime($verifycation[0]['created_dt']);
                $balance = $now - $created_dt;

                if($balance < 3600){

                    $this->redirect('/changepassword/'.$token);


                }else{
                    $this->_helper->getHelper('FlashMessenger')->addMessage('Ошибка восстановления пароля, повторите процедуру позже');
                    $this->redirect('/user/login/failed');
                }
            }else{
                $this->_helper->getHelper('FlashMessenger')->addMessage('Ошибка восстановления пароля, ссылка недействительна');
                $this->redirect('/user/login/failed');
            }
    }else{
            throw new Zend_Controller_Action_Exception('Invalid input');
    }
}
public function changePasswordAction(){

  $token = $this->getRequest()->getParam('token');
  $passForm = new Myblog_Form_ChangePass();
  $passForm->getElement('token')->setValue($token);
  $this->view->form = $passForm;

    if($this->getRequest()->isPost() && $passForm->isValid($this->getRequest()->getPost())){


        $pass =  $passForm->getValue('password');
        $tok = $passForm->getValue('token');
        $user = Doctrine_Query::create()
                ->from('Myblog_Model_Tokens t')
                ->where('t.token=?',$tok)
                ->fetchArray();

        if(count($user)){

        $newpass = Doctrine_Query::create()
            ->update('Myblog_Model_Users u')
            ->set('u.password','?',sha1($pass))
            ->where('u.id=?',$user[0]['user_id'])
            ->execute();
        }else{
            throw new Zend_Controller_Action_Exception('Invalid input');
        }
        if($newpass){
            $deltoken = Doctrine_Query::create()
                ->delete()
                ->from('Myblog_Model_Tokens t')
                ->where('t.token=?',$tok)
                ->execute();

            if($deltoken){
                $this->_helper->getHelper('FlashMessenger')->addMessage('Пароль успешно изменен! Вы можете авторизироватся с использованием нового пароля');
                $this->redirect('/user/sendtoken/success');
            }else{
                $this->_helper->getHelper('FlashMessenger')->addMessage('Ошибка восстановления пароля, повторите процедуру позже');
                $this->redirect('/user/login/failed');
            }
        }else{
            $this->_helper->getHelper('FlashMessenger')->addMessage('Ошибка восстановления пароля, повторите процедуру позже');
            $this->redirect('/user/login/failed');
        }
    }
}

    public function checkAction(){

        $form = new Myblog_Form_PassRecovery();

        $form->isValid($this->getRequest()->getPost());
        $json=$form->getMessages();
            foreach($json as $v=>$k){
                $this->view->$v = $k;
            }
    }
    public function checkingAction(){

        $form = new Myblog_Form_ChangePass();

        $form->isValid($this->getRequest()->getParams());
        $json=$form->getMessages();
        foreach($json as $v=>$k){
            $this->view->$v = $k;
        }
    }


	public function userprofileAction(){
        $auth = Zend_Auth::getInstance()->getIdentity();
		if(Zend_Auth::getInstance()->hasIdentity() && $auth->status == 'user'){
						$q=Doctrine_Query::create()
							->from('Myblog_Model_Users u')
							->where('u.userlogin=?',$auth->login)
							->fetchArray();
						if(!empty($q)){
						$this->view->userprofile=$q;
						}
		}elseif($auth->status === 'admin' || $auth->status === 'demo_admin'){

            $this->view->userprofile = $auth->data;
        }
        if($this->_helper->getHelper("FlashMessenger")->getMessages())
        {
            $this->view->message = $this->_helper->getHelper("FlashMessenger")->getMessages();
        }
	}
			
    public function logoutAction()
    {
    	 $auth = Zend_Auth::getInstance();
    	 $auth->clearIdentity();
    	 Zend_Session::destroy();
    	 $this->redirect('/main');
    		
    }
    public function activateAction(){

        if($this->getRequest()->isGet()){
            $v = array('token'=>array('NotEmpty'));
            $f = array('token'=>array('StripTags','StringTrim'));
            $input = new Zend_Filter_Input($f,$v);
            $input->setData($this->getRequest()->getParams());
            if($input->isValid()){
                $q = Doctrine_Query::create()
                    ->from('Myblog_Model_Tokens t')
                    ->where('t.token=?',$input->token)
                    ->fetchArray();

                if($q){
                    $created_timestamp =  strtotime($q[0]['created_dt']);
                    $current_timestamp =time();
                    $expires_time = 86400;
                    $remaining_time = $current_timestamp-$created_timestamp;
                    //var_dump($q);exit;
                        if($remaining_time < $expires_time){

                            $users = Doctrine_Query::create()
                                ->update('Myblog_Model_Users u')
                                ->set('u.active','?',1)
                                ->where('u.id=?',$q[0]['user_id'])
                                ->execute();
                            if($users){
                                $tokens = Doctrine_Query::create()
                                    ->from('Myblog_Model_Tokens t')
                                    ->delete()
                                    ->where('t.user_id=?',$q[0]['user_id'])
                                    ->execute();

                                $this->_helper->getHelper('FlashMessenger')->addMessage('Регистрация нового пользователя успешно завершена.');
                                $this->redirect('/user/login/success');
                            }else{
                                $this->_helper->getHelper('FlashMessenger')->addMessage('Активация учетной записи потерпела неудачу');
                                $this->redirect('/user/login/failed');
                            }

                        }else{
                            $this->_helper->getHelper('FlashMessenger')->addMessage('Активационная ссылка просрочена');
                            $this->redirect('/user/login/failed');
                        }
                }else{
                    throw new Zend_Controller_Action_Exception('Invalid input');
                }

            }else{
                    throw new Zend_Controller_Action_Exception('Invalid input');
            };
        }
    }
    public function successAction()
    {
        if($this->_helper->getHelper('FlashMessenger')->getMessages()){
            $this->view->messages=$this->_helper->getHelper('FlashMessenger')->getMessages();
            $this->getResponse()->setHeader('Refresh','3; URL=/main');
        }
        else{
            $this->redirect('/main');
        }
    }
    public function failedAction()
    {
        if($this->_helper->getHelper('FlashMessenger')->getMessages()){
            $this->view->messages=$this->_helper->getHelper('FlashMessenger')->getMessages();
            $this->getResponse()->setHeader('Refresh','8; URL=/main');
        }
        else{
            $this->redirect('/main');
        }
    }
}